package pwd.allen;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.JavaModule;

import java.lang.instrument.Instrumentation;

/**
 * 使用byte-buddy修改finder的校验方法
 *
 * @author 门那粒沙
 * @create 2021-03-09 21:59
 **/
public class PreMainAgent {

    public static void premain(String agentArgs, Instrumentation inst) {
        AgentBuilder.Transformer transformer = new AgentBuilder.Transformer() {
            @Override
            public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule) {
                // method指定哪些方法需要被拦截，ElementMatchers.any指定了所有的方法
                // 声明intercept拦截器
                return builder.method(ElementMatchers.named("ensureSupported"))
                        // 委托给MyInterceptor处理
                        .intercept(MethodDelegation.to(MyInterceptor.class));
            }
        };

        // type指定了agent拦截的包名以pwd.allen作为前缀
        // 指定了transformer
        // 将配置安装到Instrumentation
        new AgentBuilder.Default().type(ElementMatchers.<TypeDescription>nameMatches("org.flywaydb.core.internal.database.oracle.OracleDatabase"))
                .transform(transformer).installOn(inst);
    }
}
